package cn.com.shuyangyang.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.shuyangyang.controller.response.EmptyResponse;
import cn.com.shuyangyang.controller.response.ExceptionResponse;
import cn.com.shuyangyang.controller.response.NormalResponse;
import cn.com.shuyangyang.controller.response.Response;
import cn.com.shuyangyang.domain.Dept;
import cn.com.shuyangyang.domain.EnumStatus;
import cn.com.shuyangyang.domain.UserDept;
import cn.com.shuyangyang.service.DeptService;
import cn.com.shuyangyang.service.UserDeptService;

@Controller
@RequestMapping("/dept/")
public class DepatMentController {

	Logger	logger	= LoggerFactory.getLogger(DepatMentController.class);

	@Autowired
	private DeptService		deptService;

	@Autowired
	private UserDeptService	userDeptService;

	@RequestMapping("loadDept")
	@ResponseBody
	public Response loadDept(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String deptId = request.getParameter("deptId");
			Dept dept = new Dept();
			dept.setDept_id(deptId);
			Dept dpt = deptService.findDepts(dept).get(0);
			if (dpt != null) {
				return new NormalResponse(dpt);
			} else {
				return new EmptyResponse("部门数据");
			}
		} catch (Exception e) {
			logger.error("读取部门环节出现异常：", e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}

	@RequestMapping("editDept")
	@ResponseBody
	public Response editDept(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String deptId = request.getParameter("dept_id");
			String deptName = request.getParameter("dept_name");
			String dept_status = request.getParameter("dept_status");
			String description = request.getParameter("description");
			Dept dept = new Dept();
			dept.setDept_id(deptId);
			dept.setDept_name(deptName);
			dept.setDept_status(EnumStatus.AVAILABLE.toString().equals(
					dept_status) ? EnumStatus.AVAILABLE : EnumStatus.DISABLED);
			dept.setDescription(description);
			dept.setUpdate_time(new Date());
			deptService.updateDeptByDeptId(dept);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("编辑部门环节出现异常：", e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}

	/**
	 * 返回所有部门数据
	 * 
	 * @return
	 */
	@RequestMapping("showDept")
	@ResponseBody
	public List<Dept> Menus(HttpServletRequest req, HttpServletResponse resp) {
		List<Dept> depts = deptService.findDepts();
		try {
			List<Dept> deptList = treeDeptList(depts, "0");
			return deptList;
		} catch (Exception e) {
			logger.error("获取部门数据错误:" + e);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 返回所有部门数据，选中
	 * 
	 * @return
	 */
	@RequestMapping("showDeptBySelected")
	@ResponseBody
	public List<Dept> Dept(HttpServletRequest req, HttpServletResponse resp) {
		String userId = req.getParameter("userId");
		List<UserDept> useDepts = userDeptService.getUserDeptByUserId(userId);
		List<Dept> depts = deptService.findDepts();
		try {
			List<Dept> deptList = treeDeptList(depts, "0");
			for (UserDept userDept : useDepts) {
				for (Dept dept : depts) {
					if (userDept.getDept_id().equals(dept.getDept_id())) {
						dept.setChecked(true);
					}
				}
			}
			return deptList;
		} catch (Exception e) {
			logger.error("获取部门数据错误:" + e);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 添加上级部门
	 * 
	 * @return
	 */
	@RequestMapping("addPartenrDept")
	@ResponseBody
	public Response addPartenrDept(HttpServletRequest req,
			HttpServletResponse resp) {
		try {
			String deptFatherId = req.getParameter("deptFatherId");
			String deptName = req.getParameter("dept_name");
			String deptStatus = req.getParameter("dept_status");
			String description = req.getParameter("description");
			String fatherId = "";
			Dept dept = new Dept();
			if (deptFatherId.equals("0")) {
				fatherId = "0";
			} else {
				dept.setDept_id(deptFatherId);
				List<Dept> depts = deptService.findDepts(dept);
				fatherId = depts.get(0).getDept_father_id();
			}
			Dept newdept = new Dept();
			newdept.setDept_father_id(fatherId);
			newdept.setDept_name(deptName);
			if (deptStatus.equals("AVAILABLE")) {
				newdept.setDept_status(EnumStatus.AVAILABLE);
			} else {
				newdept.setDept_status(EnumStatus.DISABLED);
			}
			newdept.setDescription(description);
			deptService.saveDept(newdept);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("添加部门数据错误:" + e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
		
	}

	/**
	 * 添加同级部门
	 * 
	 * @return
	 */
	@RequestMapping("addSameDept")
	@ResponseBody
	public Response addSameDept(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String deptFatherId = req.getParameter("deptFatherId");
			String deptName = req.getParameter("dept_name");
			String deptStatus = req.getParameter("dept_status");
			String description = req.getParameter("description");
			Dept dept = new Dept();
			dept.setDept_father_id(deptFatherId);
			dept.setDept_name(deptName);
			if (deptStatus.equals("AVAILABLE")) {
				dept.setDept_status(EnumStatus.AVAILABLE);
			} else {
				dept.setDept_status(EnumStatus.DISABLED);
			}
			dept.setDescription(description);
			deptService.saveDept(dept);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("添加部门数据错误:" + e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
		
	}

	/**
	 * 添加下级部门
	 * 
	 * @return
	 */
	@RequestMapping("addChildDept")
	@ResponseBody
	public Response addChildDept(HttpServletRequest req,
			HttpServletResponse resp) {
		try {
			String deptId = req.getParameter("deptId");
			String deptName = req.getParameter("dept_name");
			String deptStatus = req.getParameter("dept_status");
			String description = req.getParameter("description");
			Dept dept = new Dept();
			dept.setDept_father_id(deptId);
			dept.setDept_name(deptName);
			if (deptStatus.equals("AVAILABLE")) {
				dept.setDept_status(EnumStatus.AVAILABLE);
			} else {
				dept.setDept_status(EnumStatus.DISABLED);
			}
			dept.setDescription(description);
			deptService.saveDept(dept);
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("添加部门数据错误:" + e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
	}

	/**
	 * 删除部门
	 * 
	 * @return
	 */
	@RequestMapping("deleteDept")
	@ResponseBody
	public Response deleteDept(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String deptId = req.getParameter("deptId");
			Dept dept = new Dept();
			dept.setDept_id(deptId);
			deptService.deleteDeptByDeptId(dept);

			delTreeDeptList(deptId);// 递归删除子节点
			return new NormalResponse();
		} catch (Exception e) {
			logger.error("删除部门数据错误:" + e);
			e.printStackTrace();
			return new ExceptionResponse(e);
		}
		
	}

	// 递归删除子节点
	private void delTreeDeptList(String deptId) {
		Dept deptNode = new Dept();
		deptNode.setDept_id(null);
		deptNode.setDept_father_id(deptId);
		List<Dept> depts = deptService.findDepts(deptNode);
		if (depts != null && depts.size() > 0) {
			for (Dept dept : depts) {
				deptService.deleteDeptByDeptId(dept);
				delTreeDeptList(dept.getDept_id());
			}
		}
	}

	// 递归遍历树
	private static List<Dept> treeDeptList(List<Dept> deptList, String fatherId) {
		List<Dept> deptChildList = new ArrayList<Dept>();
		for (Dept dept : deptList) {
			if (fatherId.equals(dept.getDept_father_id())) {
				List<Dept> deptChildren = treeDeptList(deptList,
						dept.getDept_id());
				dept.setChildren(deptChildren);
				if (deptChildren.size() > 0) {
					dept.setLeaf(false);
					dept.setExpanded(true);// 需要展开子节点了
				} else {
					dept.setLeaf(true);
					dept.setExpanded(false);// 不需要展开子节点了
				}
				deptChildList.add(dept);
			}
		}

		for (Dept dpt : deptChildList) {
			if (dpt.getChildren() == null) {
				dpt.setLeaf(true); // 拜托，没有子节点，根节点就不用再展开了
			}
		}
		return deptChildList;
	}
}
